package cn.maigc.web.sys_user.controller;

import cn.maigc.config.imagecode.KaptchaConfig;
import cn.maigc.jwt.JwtUtils;
import cn.maigc.utils.ResultVo;
import cn.maigc.web.sys_menu.entity.*;
import cn.maigc.web.sys_menu.service.SysMenuService;
import cn.maigc.web.sys_role.entity.SysRole;
import cn.maigc.web.sys_user.entity.*;
import cn.maigc.web.sys_user.service.SysUserService;
import cn.maigc.web.sys_user_role.entity.SysUserRole;
import cn.maigc.web.sys_user_role.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysMenuService sysMenuService;

    //新增
    @PostMapping
    public ResultVo add(@RequestBody SysUser sysUser){

        sysUser.setCreateTime(new Date());
        //boolean temp = sysUserService.save(sysUser);
        sysUserService.saveUser(sysUser);
       // if(temp){
            return ResultVo.success("新增成功！");
        //}
       // return ResultVo.error("新增失败！");
    }
    //删除
    @DeleteMapping("/{userId}")
    public ResultVo delete(@PathVariable("userId") Long userId){
        //boolean temp = sysUserService.removeById(userId);
        sysUserService.deleteUser(userId);
        //if(temp){
            return ResultVo.success("删除成功！");
        //}
        //return ResultVo.error("删除失败！");
    }

    //编辑
    @PutMapping
    public ResultVo edit(@RequestBody SysUser sysUser){
        sysUser.setUpdateTime(new Date());
        //boolean temp = sysUserService.updateById(sysUser);
        sysUserService.editUser(sysUser);
        //if(temp){
            return ResultVo.success("编辑成功！");
        //}
        //return ResultVo.error("编辑失败！");
    }

    //查询
    @GetMapping("/getList")
    public ResultVo getList(UserParam param){
        //构造分页对象
        IPage<SysUser> page = new Page<>(param.getCurPage(),param.getPageSize());
        //构造查询条件
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        //条件判断
        if(StringUtils.isNotEmpty(param.getNickName())){
            wrapper.lambda().like(SysUser::getNickName,param.getNickName());
        }
        if(StringUtils.isNotEmpty(param.getPhone())){
            wrapper.lambda().like(SysUser::getPhone,param.getPhone());
        }
        wrapper.lambda().orderByDesc(SysUser::getCreateTime);

        //查询列表
        IPage<SysUser> pageList = sysUserService.page(page, wrapper);
        if(pageList != null){
            return ResultVo.success("查询成功！",pageList);
        }
        return ResultVo.error("查询失败！！");
    }

    //根据用户Id获取所的用户角色
    @GetMapping("/getRoleList")
    public ResultVo getRoleList(Long userId){

        //构建查询条件
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUserRole::getUserId,userId);
        List<SysUserRole> list = sysUserRoleService.list(wrapper);
        //存储角色ID
        List<Long> roleList = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .forEach(item -> {
                    roleList.add(item.getRoleId());
                });
        return ResultVo.success("查询成功！",roleList);
    }

    //重置密码
    @PostMapping("/resetPassword")
    public ResultVo resetPassword(@RequestBody SysUser sysUser){
        //条件构造器
        UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(SysUser::getUserId,sysUser.getUserId())
                .set(SysUser::getPassword,"666666");
        boolean temp = sysUserService.update(wrapper);
        if(temp){
            return ResultVo.success("密码重置成功！！");
        }
        return  ResultVo.error("密码重置失败！！");
    }

    //获取图片验证码
    @PostMapping("/getImage")
    public ResultVo getImage(HttpServletRequest request){
        //获取Session对象
        HttpSession session = request.getSession();
        //生成验证码
        String text = defaultKaptcha.createText();
        //存储在Session中
        session.setAttribute("code",text);
        //生成图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            //写入内存中
            ImageIO.write(image,"jpg",outputStream);
            //转换为Base64
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(outputStream.toByteArray());
            String str = "data:image/jpeg;base64,"+base64.replaceAll("\r\n","");

            return ResultVo.success("验证码获取成功！",str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //登录
    @PostMapping("/login")
    public ResultVo login(HttpServletRequest request,@RequestBody LoginParam param){
        //获取前端传递过来的验证码
        String code1 = param.getCode();
        //获取Session
        HttpSession session = request.getSession();
        String  code2 = (String)session.getAttribute("code");
        //判断session中有无验证码
        if(StringUtils.isEmpty(code2)){
            return ResultVo.error("验证码过期！");
        }
        //两个验证码是否相同
        if(!code2.equals(code1)){
            return ResultVo.error("验证码不正确！");
        }

        //查询条件
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUser::getUsername,param.getUsername())
                .eq(SysUser::getPassword,param.getPassword());
        SysUser user = sysUserService.getOne(wrapper);
        if(user == null){
            return ResultVo.error("用户名或密码不正确！！！");
        }
        //返回用户信息和token
        LoginVo vo = new LoginVo();
        vo.setUserId(user.getUserId());
        vo.setNickName(user.getNickName());
        //生成token
        vo.setToken(jwtUtils.createToken(user.getUserId().toString(),user.getNickName()));
        return ResultVo.success("登录成功！",vo);
    }
    //查询菜单树
    @GetMapping("/getAssingTree")
    public ResultVo getAssingTree(AssignTreeParam param){
        AssignTreeVo assignTree = sysUserService.getAssignTree(param);
        return ResultVo.success("查询成功",assignTree);
    }

    //修改用户密码的方法
    @PostMapping("/updatePassword")
    public ResultVo updatePassword(@RequestBody UpdatePasswordParam param){
        //查询用户

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUser::getUserId,param.getUserId());
        SysUser user = sysUserService.getOne(wrapper);
        //判断密码是否正确
        if(!user.getPassword().equals(param.getOldPassword())){
            return ResultVo.error("旧密码不正确！");
        }
        //修改密码
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysUser::getUserId,param.getUserId())
                .set(SysUser::getPassword,param.getNewPassword());
        if(sysUserService.update(updateWrapper)){
            return ResultVo.success("修改密码成功！");
        }
        return ResultVo.error("修改密码失败！");
    }

    //获取用户权限的方法
    @GetMapping("/getUserInfo")
    public ResultVo getUserInfo(Long userId){
        //根据id查询用户信息
        SysUser user = sysUserService.getById(userId);
        List<SysMenu> menuList = null;
        //判断是否是超级管理员
        if (StringUtils.isNotEmpty(user.getIsAdmin()) && "1".equals(user.getIsAdmin())) {
            //超级管理员,直接全部查询
            menuList = sysMenuService.list();
        } else {
            menuList = sysMenuService.getMenuByUserId(user.getUserId());
        }
        //获取菜单表的code字段
        List<String> collect = Optional.ofNullable(menuList).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null && StringUtils.isNotEmpty(item.getCode()))
                .map(item -> item.getCode())
                .collect(Collectors.toList());
        //设置返回值
        UserInfo userInfo = new UserInfo();
        userInfo.setName(user.getNickName());
        userInfo.setUserId(user.getUserId());
        userInfo.setPermissions(collect.toArray());
        return ResultVo.success("查询成功", userInfo);
    }

    //获取所有菜单
    @GetMapping("/getMenuList")
    public ResultVo getMenuList(Long userId){
        //获取用户信息
        SysUser user = sysUserService.getById(userId);
        //获取用户的权限信息
        List<SysMenu> sysMenuList = null;
        //判断是否是超级管理员
        if (StringUtils.isNotEmpty(user.getIsAdmin()) && user.getIsAdmin().equals("1")) {
            sysMenuList = sysMenuService.list();
        } else {
            sysMenuList = sysMenuService.getMenuByUserId(userId);
        }
        //菜单数据，查询类型为 0和1的数据
        List<SysMenu> menuList = Optional.ofNullable(sysMenuList).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null &&  StringUtils.isNotEmpty(item.getType())
                        && !item.getType().equals("2")).collect(Collectors.toList());
        //组装菜单数据类型RouterVo
        List<RouterVo> router = MakeMenuTree.makeRouter(menuList, 0L);
        return ResultVo.success("查询成功", router);
    }

}
